/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.SQL;

import Server.Helper.Analyzer;
import java.util.Vector;
import Server.MyDataType.Attribute_Value;
import Server.MyDataType.MyDataDynamic;
import Server.MyDataType.MyRowData;
import Server.lastproject.XMLManage;

/**
 *
 * @author CANG
 */
public class InsertCommand  extends MyCommand
{
    public InsertCommand(String command)
    {
        super(command);
    }
    
    public MyDataDynamic analysic(String command)
    {        
        MyDataDynamic data = new MyDataDynamic();
        // Chuẩn hóa
        command = new Analyzer().MakeCommandStandardization4InsertSelect(command);
        String[] lstFirt = command.split(" ");
        if(lstFirt[0].toUpperCase().compareTo("INSERT") == 0)
        {
            command= "";
            for(int i = 1; i<lstFirt.length; i++)
                command += lstFirt[i] + " ";
            command = command.trim();
        }
        boolean bExecute = false;
        try
        {
            XMLManage xmlManage = new XMLManage();


            String sInto = splitFirstString(command, " ");        
            if( sInto != null && sInto.toLowerCase().compareTo("into") == 0)
            {
                //tach  into
                String sNameTable = splitGetComponentBefore_Parenthesis(_sCommand);

                //kiem tra ton tai table trong csdl
                bExecute = xmlManage.checkExistTable(sNameTable);
                if(!bExecute)
                    return null;
                
                if(sInto != null )
                {
                    int len = _sCommand.length();
                    boolean bHaveColumn = false;
                    boolean bValueCorrect = true;
                    String[] lstNameColumn = null;
                    String[] lstValues = null;
                    
                    //neu thuoc truong hop:
                    /*                 
                        INSERT INTO table_name (column1, column2, column3,...)
                        VALUES (value1, value2, value3,...)
                    */ 
                    if(_sCommand.charAt(0) == '(' || (_sCommand.charAt(0) == ' ' && _sCommand.charAt(1) == '('))
                    {
                        bHaveColumn = true;
                        
                        int[] lstIndex_Parenthesises = getIndexCouple_Parenthesis(_sCommand);
                        if( lstIndex_Parenthesises[0] == -1 || lstIndex_Parenthesises[1] == -1)
                            return null;
                        
                        String sSubCommandTable = _sCommand.substring(lstIndex_Parenthesises[0] + 1, lstIndex_Parenthesises[1]);
                        _sCommand = _sCommand.substring(lstIndex_Parenthesises[1] + 1, len);                    
                        lstNameColumn = sSubCommandTable.split(",");
                        for(int i = 0; i < lstNameColumn.length; i++)
                        {
                            lstNameColumn[i] = lstNameColumn[i].trim();
                        }                        
                    }
                    //ngoai tra neu thuoc truong hop
                    /*                 
                        INSERT INTO table_name
                        VALUES (value1, value2, value3,...)
                    */ 
                    else
                    {
                        //lay theo thu tu mac dinh name column
                        lstNameColumn = xmlManage.getAllNameColumn(sNameTable);
                    }
                    
                    boolean bCheckExistColumn = xmlManage.checkListColumn(sNameTable, lstNameColumn);
                    
                    //neu la cau lenh cap 1
                    _sCommand = _sCommand.trim();
                    if(_sCommand.charAt(0) == 'v' || _sCommand.charAt(0) == 'V')
                    {
                        String sValue = _sCommand.substring(0, 6);
                        len = _sCommand.length();
                        boolean khongkhoangcach  = _sCommand.charAt(6) == '(' ;
                        boolean khoangtrang = (_sCommand.charAt(6) == ' ' && _sCommand.charAt(7) == '(');
                        if(sValue.toLowerCase().compareTo("values") == 0 && 
                                (khoangtrang || khongkhoangcach ))
                        {
                            _sCommand = _sCommand.trim();
                            int indexplit = 7;
                            if(khoangtrang)
                                indexplit = 8;
                            String sSubCommandValues = _sCommand.substring(indexplit, len - 1);
                            
                            lstValues = sSubCommandValues.split(",");
                            
                            if(lstNameColumn != null && lstNameColumn.length != lstValues.length && !bCheckExistColumn)
                            {
                                return null;                        
                            }
                            
                            for(int i = 0; i < lstValues.length; i++)
                            {
                                lstValues[i] = lstValues[i].trim();
                                                                
                                if( lstValues[i].indexOf("'") >= 0 )
                                {
                                    lstValues[i] = lstValues[i].substring(1, lstValues[i].length() - 1); 
                                    String type = xmlManage.getTypeAttribute(sNameTable, lstNameColumn[i]);
                                    if(type == null || !type.equals("string"))
                                    {
                                        bValueCorrect = false;
                                        break;
                                    }
                                } 
                                else
                                {
                                    String type = xmlManage.getTypeAttribute(sNameTable, lstValues[i]);
                                    if(type == null || !type.equals("float"))
                                    {
                                        bValueCorrect = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        //CÂU LỆNH CẤP 2 --> chưa xử lý vì còn lệ thuộc vào câu lệnh khác
                        //ở đây mặc định câu lệnh cấp 2 là câu lệnh select
                        String sSelect = splitFirstString(_sCommand, " ");                                                
                        sSelect = sSelect.toLowerCase();
                        if(sSelect.equals("select"))
                        {
                            SelectCommand selectCommand = new SelectCommand(_sCommand);
                            MyDataDynamic myData = selectCommand.Analysic_SelectCommand(_sCommand);
                                                       
                            int iRowData = myData._vtRowData.size();
                            for(int i  = 0; i < iRowData; i++)
                            {
                                MyRowData rowData = myData._vtRowData.elementAt(i);
                                bExecute = xmlManage.insertRow(sNameTable, lstNameColumn, rowData);
                                if(!bExecute)
                                {
                                    break;
                                }
                            }                                                        
                            
                        }   
                        return data;
                    }
                                        
                    if(lstNameColumn != null && lstValues != null && lstNameColumn.length != lstValues.length && !bCheckExistColumn && !bValueCorrect )
                    {
                        return null;
                    }
                    
                    Vector<Attribute_Value> vtValues = createListAttribute(lstNameColumn, lstValues);
                    bExecute = xmlManage.insertRow(sNameTable, vtValues);
                    
                    xmlManage.saveToFile();
                }
            }
        }
        catch(Exception ex)
        {
            return null;
        }
        return data;        
    }

}
